package com.wyait.manage.config.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wyait.manage.config.security.filter.VerifyUserException;
import com.wyait.manage.entity.ResponseResult;
import com.wyait.manage.utils.IStatusMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author xiyang.ycj
 * @since Jun 25, 2019 17:09:13 PM
 */
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler  {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFailureHandler.class);
    private static final ObjectMapper mapper = new ObjectMapper();
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        LOGGER.error("登录错误 [{}] ",e.getClass().getName());
        ResponseResult responseResult = new ResponseResult();
        String message;
        if (e instanceof VerifyUserException) {
            message = e.getMessage();
        }else if (e instanceof UsernameNotFoundException
                ||e instanceof BadCredentialsException) {
            message = "账户不存在或账户密码错误，请联系管理员!";
        }else if (e instanceof LockedException) {
            message = "账户被锁定，请联系管理员!";
        } else if (e instanceof CredentialsExpiredException) {
            message = "证书过期，请联系管理员!";
        } else if (e instanceof AccountExpiredException) {
            message = "账户过期，请联系管理员!";
        } else if (e instanceof DisabledException) {
            message = "账户被禁用，请联系管理员!";
        } else {
            message = "登录失败!";
        }
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = response.getWriter();

        responseResult.setCode(IStatusMessage.SystemStatus.ERROR.getCode());
        responseResult.setMessage(message);
        writer.write(mapper.writeValueAsString(responseResult));
        writer.flush();
        writer.close();
    }
}
